package com.com.util;

public class Game {
	
	private final int FIELD_SIZE_X = 10;
	private final int FIELD_SIZE_Y = 10;
	private final int PLAYERS_COUNT = 2;
	private final int PLAYERS_PER_PLAYER = 20;
	
	private boolean[][][] ships;
	private ShootResult[][][] shoots;
	
	private int[] shipsCount;
	private int currentPlayer;
	
	public Game() {
		currentPlayer = 0;
		ships = new boolean[FIELD_SIZE_X + 1][FIELD_SIZE_Y + 1][PLAYERS_COUNT];
		shoots = new ShootResult[FIELD_SIZE_X + 1][FIELD_SIZE_Y + 1][PLAYERS_COUNT];
		// initialize all shoots array
		shipsCount = new int[PLAYERS_COUNT];
		for (int i = 0; i < PLAYERS_COUNT; ++i)
			shipsCount[i] = PLAYERS_PER_PLAYER; 
	}

	// WHY DO I NEED THIS?
	public int getCurrentPlayer() {
		return currentPlayer;
	}
	
	public ShootResult shoot(int x, int y) {
		int nextPlayer = (currentPlayer + 1) % 2;
		if (ships[x][y][nextPlayer]) {
			ships[x][y][nextPlayer] = false;
			--shipsCount[nextPlayer];
			shoots[x][y][currentPlayer] = getShootResult(x, y, nextPlayer);
		} else {
			shoots[x][y][currentPlayer] = ShootResult.PAST;
		}
		ShootResult result = shoots[x][y][currentPlayer];
		currentPlayer = nextPlayer;
		return result;
	}
	
	public void setShips(boolean[][] ships, int playerNumber) {
		for (int i = 0; i < FIELD_SIZE_X; ++i)
			for (int j = 0; j < FIELD_SIZE_Y; ++i)
				this.ships[i][j][playerNumber] = ships[i][j];
	}
	
	// should be called only when the ship is damaged
	private ShootResult getShootResult(int x, int y, int player) {
		if (!hasNeighbourShips(x, y, player))
			return ShootResult.KILLED;
		else
			return ShootResult.DAMAGED;
	}
	
	private boolean hasNeighbourShips(int x, int y, int player) {
		return ships[x - 1][y - 1][player] || ships[x - 1][y][player] || ships[x - 1][y + 1][player] ||
				ships[x + 1][y - 1][player] || ships[x + 1][y][player] || ships[x + 1][y + 1][player] ||
				ships[x][y - 1][player] || ships[x][y + 1][player];
	}
	
	public boolean hasShips(int player) {
		return shipsCount[player] > 0;
	}

}
